/*
 * @Author: 徐建辰
 * @Date: 2021-11-04 16:09:30
 * @LastEditTime: 2021-11-04 17:08:40
 * @LastEditors: Please set LastEditors
 * @Description: 日历-月份组件
 */
import React from 'react'
import PropTypes from 'prop-types'
import Week from './Week'
import './datepicker.css'

function Month(props) {
  const {startTimeMonth, onSelect} = props
  // 获取并遍历当前月的所有日期，以7天为一组渲染（以每天的零时刻代表这一天）
  const startDay = new Date(startTimeMonth)
  const currentDay = new Date(startTimeMonth)
  let days = []
  while (currentDay.getMonth() === startDay.getMonth()) { //只要相等，就一直遍历，直到月份递增
    // 放入这一天的零时刻
    days.push(currentDay.getTime())
    currentDay.setDate(currentDay.getDate() + 1)
  }
  // 如果1号不是周一，前面就要补上空白，同理每月最后一天也是 （当前月是周几，就补齐这个数字 - 1，周日要补齐6个）
  days = new Array(startDay.getDay() ? startDay.getDay() - 1 : 6).fill(null).concat(days)
  const lastDay = new Date(days[days.length - 1])
  // 计算补齐长度
  days = days.concat(new Array(lastDay.getDay() ? 7 - lastDay.getDay() : 0).fill(null))
  // 把所有日期以周为单位进行分组
  const weeks = []
  for (let i = 0; i < days.length / 7; i++) {
    const week = days.slice(i * 7, (i + 1) * 7)
    weeks.push(week)
  }

  return (
    <table className="date-table">
      {/* 表头 */}
      <thead>
        <tr>
          {/* 一周是7天，要跨7列 */}
          <td colSpan="7">
            <h5>{startDay.getFullYear()}年{startDay.getMonth() + 1}月</h5>
          </td>
        </tr>
      </thead>
      <tbody>
        <tr className="date-table-weeks">
          <th>周一</th>
          <th>周二</th>
          <th>周三</th>
          <th>周四</th>
          <th>周五</th>
          <th className="weekend">周六</th>
          <th className="weekend">周天</th>
        </tr>
        {weeks.map((week, index) => <Week key={index} days={week} onSelect={onSelect} />)}
      </tbody>
    </table>
  )
}

Month.propTypes = {
  startTimeMonth: PropTypes.number.isRequired,
  onSelect: PropTypes.func.isRequired,
}

export default Month
